package cn.wowjoy.office.materialmanage.materialdetail;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.StockDetailAdapter;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.GoodsDetailResponse;
import cn.wowjoy.office.data.response.StockDetailListResponse;
import cn.wowjoy.office.databinding.ActivityMaterialDetailBinding;
import cn.wowjoy.office.utils.ImageSelectorUtils;
import cn.wowjoy.office.utils.PreferenceManager;

@Route(path = "/materialmanage/materialdetail/materiadetail")
public class MaterialDetailActivity extends NewBaseActivity<ActivityMaterialDetailBinding,MaterialDetialViewModel> implements View.OnClickListener {

    private static final int REQUEST_CODE = 0x00000011;
    private  Menu menu;
    @Autowired
    String goodsCode;
    @Autowired
    boolean isCanEdit;
    @Inject
    PreferenceManager preferenceManager;
    private MDialog waitDialog;
    public static void startActivity(Context context,String code){
        Intent intent = new Intent(context,MaterialDetailActivity.class);
        intent.putExtra(Constants.GOODS_CODE,code);
        context.startActivity(intent);
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewmodel(viewModel);
        setSupportActionBar(binding.toolbar);
//        goodsCode = getIntent().getStringExtra(Constants.GOODS_CODE);
        changeView();
        binding.noticeRl.setEnabled(isCanEdit);
        binding.image.setEnabled(isCanEdit);
        binding.noticeRl.setOnClickListener(this);
        binding.image.setOnClickListener(this);
        if (!TextUtils.isEmpty(goodsCode)){
           obseverModel();
        }

//        binding.image.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                List<String> images  = new ArrayList<>();
////                images.add(url);
//                images.add(filePath);
//                PhotoPreviewDialog previewDialog = new PhotoPreviewDialog.Builder()
//                        .needHeader(preferenceManager.getHeaderToken())
//                        .index(0)
//                        .path(images)
//                        .build();
//                previewDialog.setIndex(0);
//                previewDialog.show(getSupportFragmentManager(), null);
//
//                return false;
//            }
//        });
    }

    private void changeView(){
        binding.materialTitle.setVisibility(isCanEdit ? View.VISIBLE : View.GONE);
        binding.materialDetail.setVisibility(isCanEdit ? View.VISIBLE : View.GONE);
        binding.stockTitle.setVisibility(isCanEdit ? View.VISIBLE : View.GONE);
        binding.stockInfo.setVisibility(isCanEdit ? View.VISIBLE : View.GONE);
        binding.stockDetailTitle.setVisibility(isCanEdit ? View.GONE : View.VISIBLE);
        binding.stockRecyclerview.setVisibility(isCanEdit ? View.GONE : View.VISIBLE);
    }
    @Override
    public void onClick(View v) {
        ImageSelectorUtils.openPhoto(MaterialDetailActivity.this,REQUEST_CODE,true,1);
    }



    @Override
    protected void onResume() {
        super.onResume();
        openBroadCast();

    }

    @Override
    protected void onStop() {
        super.onStop();
        closeBroadCast();
    }


    private boolean isHasPoto = false;
    private boolean isHasWrite = false;
    private CommonDialog noticeChangeDialog;
    private void showNoticeChange(String msg){
        noticeChangeDialog = new CommonDialog.Builder()
                .setTitle("提醒")
                .setContent("是否替换之前条形码")
                .setCancelBtn("否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeChangeDialog.dismiss();
                    }
                })
                .setConfirmBtn("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        binding.code.setText(msg);
                        barCode = msg;
                        noticeChangeDialog.dismiss();
                        if (!isHasWrite){
                            isHasWrite = true;
                            invalidateOptionsMenu();
                        }
                    }
                })
                .create();
        noticeChangeDialog.show(getSupportFragmentManager(),null);
    }
    private String barCode;
    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        if(isCanEdit) {
            if (!isHasWrite) {
                if (isLoadcode) {
                    showNoticeChange(msg);
                } else {
                    binding.code.setText(msg);
                    isHasWrite = true;
                    barCode = msg;
                    invalidateOptionsMenu();
                }

            } else {
                showNoticeChange(msg);
            }
            isHasSave = false;
        }

    }

    private CommonDialog noticeSaveDialog;
    private void noticeSave(){
        noticeSaveDialog = new CommonDialog.Builder()
                .setTitle("退出")
                .setContent("您还未保存，是否退出")
                .setCancelBtn("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
                    }
                })
                .setConfirmBtn("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
//                        finish();
                        complete();

                    }
                })
                .create();
        noticeSaveDialog.show(getSupportFragmentManager(),null);
    }

    private String url;
    private boolean isLoadcode = false;
    public void setSaveStatus(){
        isHasSave = true;
        restValue();
    }
     private void restValue(){
         isHasPoto = false;
         isHasWrite = false;
         invalidateOptionsMenu();
         barCode = null;
         imagePaths = null;
     }

    private boolean isHasSave = false;
    private void setModel(GoodsDetailResponse goodsDetailResponse){
        if (null != goodsDetailResponse){
            if (isCanEdit){
                binding.noticeTv.setText("点击上传照片");
                binding.code.setText("请扫码录入");
            } else {
                binding.noticeTv.setText("暂无图片");
                binding.code.setText("暂未录入");
            }
            binding.setToken(preferenceManager.getHeaderToken());
            binding.setModel(goodsDetailResponse);
            if (!TextUtils.isEmpty(goodsDetailResponse.getBarCode())){
                isLoadcode = true;
                binding.code.setText(goodsDetailResponse.getBarCode());
            }
            if (!TextUtils.isEmpty(goodsDetailResponse.getPictureUrl())){
                binding.noticeRl.setVisibility(View.GONE);
                binding.image.setVisibility(View.VISIBLE);
            } else {
                binding.noticeRl.setVisibility(View.VISIBLE);
                binding.image.setVisibility(View.GONE);
            }
            url = goodsDetailResponse.getPictureUrl();

        }
    }

    private void setStockList(StockDetailListResponse stockList){
        if(!isCanEdit && null != stockList){
            //设置库存列表信息
            binding.stockTotal.setText("合计："+stockList.getTotalCount());
            StockDetailAdapter adapter = new StockDetailAdapter(stockList.getStockDetailResponseList());
           LRecyclerViewAdapter lAdapter = new LRecyclerViewAdapter(adapter);
            binding.stockRecyclerview.setLayoutManager(new LinearLayoutManager(this));
            binding.stockRecyclerview.setAdapter(lAdapter);
            binding.stockRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
            binding.stockRecyclerview.setPullRefreshEnabled(false);
            binding.stockRecyclerview.setLoadMoreEnabled(false);
        }
    }
    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }

    }
    private void obseverModel(){
        if (isCanEdit) {
            viewModel.getDetail(goodsCode).observe(this, new Observer<LiveDataWrapper<GoodsDetailResponse>>() {
                @Override
                public void onChanged(@Nullable LiveDataWrapper<GoodsDetailResponse> goodsDetailResponseLiveDataWrapper) {
                    switch (goodsDetailResponseLiveDataWrapper.status) {
                        case LOADING:
                            clearDialog();
                            waitDialog = CreateDialog.waitingDialog(MaterialDetailActivity.this);
                            break;
                        case SUCCESS:
                            waitDialog.dismiss();
                            setModel(goodsDetailResponseLiveDataWrapper.data);
                            break;
                        case ERROR:
                            waitDialog.dismiss();
                            handleException(goodsDetailResponseLiveDataWrapper.error, true);
                            break;
                    }
                }
            });
        } else {
            viewModel.getStockDetailList(goodsCode).observe(this, new Observer<LiveDataWrapper<StockDetailListResponse>>() {
                @Override
                public void onChanged(@Nullable LiveDataWrapper<StockDetailListResponse> stockDetailListResponseLiveDataWrapper) {
                    switch (stockDetailListResponseLiveDataWrapper.status) {
                        case LOADING:
                            clearDialog();
                            waitDialog = CreateDialog.waitingDialog(MaterialDetailActivity.this);
                            break;
                        case SUCCESS:
                            waitDialog.dismiss();
                            setModel(stockDetailListResponseLiveDataWrapper.data.getGoodsDetailResponse());
                            setStockList(stockDetailListResponseLiveDataWrapper.data);
                            break;
                        case ERROR:
                            waitDialog.dismiss();
                            handleException(stockDetailListResponseLiveDataWrapper.error, true);
                            break;
                    }
                }
            });
        }
    }
    @Override
    protected void refreshError() {
        super.refreshError();
        if (!TextUtils.isEmpty(goodsCode)){
            obseverModel();
        }

    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.errorRoot;
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        if (!isHasSave && (isHasPoto || isHasWrite)){
           noticeSave();
        } else {
            complete();
            super.onBackPressed();
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (isHasWrite | isHasPoto){
            menu.getItem(0).setVisible(true).setEnabled(true);
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.save,menu);
        this.menu = menu;
        menu.getItem(0).setVisible(isCanEdit).setEnabled(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.save:
                //
//                Toast.makeText(this,"enable才能点击",Toast.LENGTH_SHORT).show();
                viewModel.saveInfo(goodsCode,barCode,imagePaths).observe(this, new Observer<LiveDataWrapper<ResultEmpty>>() {
                    @Override
                    public void onChanged(@Nullable LiveDataWrapper<ResultEmpty> resultEmptyLiveDataWrapper) {
                        switch (resultEmptyLiveDataWrapper.status){
                            case LOADING:
                                clearDialog();
                                waitDialog = CreateDialog.waitingDialog(MaterialDetailActivity.this);
                                break;
                            case SUCCESS:
                                waitDialog.dismiss();
                                setSaveStatus();
                                break;
                            case ERROR:
                                waitDialog.dismiss();
                                handleException(resultEmptyLiveDataWrapper.error,false);
                                break;
                        }
                    }
                });

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private String filePath;
    private List<String> imagePaths;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
            filePath = images.get(0);
            binding.noticeRl.setVisibility(View.GONE);
            binding.image.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(new File(images.get(0)))
                    .centerCrop()
                    .into( binding.image);
            //每次获取本地图片后进行压缩，因为压缩需要时间约1s,异步返回，保证一般情况下可以在保存操作之前压缩完成
            Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
            imagePaths = new ArrayList<>();
            imagePaths.add(filePath);

            Tiny.getInstance().source(filePath).asFile().withOptions(options).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, String outfile) {
                    //return the compressed file path
                    Log.e("compress","onSuccess="+outfile);
                    if (isSuccess){
                        Log.e("compress_success","onSuccess="+outfile);
                        imagePaths.add(outfile);

                    }
                }
            });
            if (!isHasPoto){
                isHasPoto = true;
                invalidateOptionsMenu();
            }

            isHasSave = false;
        }
    }

    private void complete(){
        Intent intent = new Intent();
        intent.putExtra(Constants.IS_NEED_REFRESH, isHasSave);
        setResult(RESULT_OK, intent);
        finish();
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_detail;
    }

    @Override
    protected Class<MaterialDetialViewModel> getViewModel() {
        return MaterialDetialViewModel.class;
    }
}
